package com.softwinner.awbt.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
import android.widget.TextView;

import com.softwinner.awbt.R;
import com.softwinner.awbt.activity.MainActivity;
import com.softwinner.awbt.common.BTApplication;
import com.softwinner.awbt.dao.Contact;
import com.softwinner.awbt.dao.ContactDao;
import com.softwinner.awbt.listener.ContactListener;
import com.softwinner.awbt.utils.LOG;

import java.util.ArrayList;
import java.util.List;


/**
 * A fragment representing a list of Items.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class ContactsFragment extends BaseFragment implements ContactListener {

    private List<Contact> mContacts = new ArrayList<>();
    private TextView mSyncTextView;
    private RecyclerView mRecyclerView;
    private MainActivity mActivity;
    private ContactsAdapter mAdapter;

    private static ContactListener sContactListener;
    private ProgressDialog mProgressDialog;
    private SearchView mSearchView;

    private static final int MSG_SYNC_TIMEOUT = 0xFD01;
    private final int SYNC_MAX_TIME = 10000;
    private boolean isLoadFromDevice;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public ContactsFragment() {
        sContactListener = this;
    }

    @SuppressWarnings("unused")
    public static ContactsFragment newInstance() {
        return new ContactsFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_contacts, container, false);

        // Set the adapter
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new ContactsAdapter(mContacts, new OnListFragmentInteractionListener() {

            @Override
            public void onListFragmentInteraction(Contact item) {
                mActivity.callPhone(item.getNumber());
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        mSyncTextView = (TextView) view.findViewById(R.id.sync_tv);
        mSyncTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadContacts();
            }
        });
        mSearchView = (SearchView) view.findViewById(R.id.searchView);
        if (mContacts.size() > 0) {
            mSyncTextView.setVisibility(View.GONE);
        }

        if (BTApplication.getInstance().getStatus() <= BTApplication.STATUS_DISCONNECTED) {
            mSyncTextView.setVisibility(View.GONE);
        }

        return view;
    }

    private void loadContacts() {
        showProgressDialog();
        mHandler.sendEmptyMessageDelayed(MSG_SYNC_TIMEOUT, SYNC_MAX_TIME);
        mContacts = BTApplication.getInstance().getDaoSession().getContactDao().queryBuilder()
                .where(ContactDao.Properties.Address.eq(BTApplication.getInstance()
                        .getCurrentAddress())).orderAsc(ContactDao.Properties.Name).list();
        LOG.d("loadContacts   contacts size =" + mContacts.size());
        if (mContacts.size() == 0) {
            if (mActivity == null) {
                return;
            }
            isLoadFromDevice = true;
            mActivity.syncContacts();
        } else {
            isLoadFromDevice = false;
            onSyncContactDone();
        }


    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (context instanceof MainActivity) {
            mActivity = (MainActivity) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        sContactListener = null;
    }

    @Override
    public void onConnected() {
        if (mSyncTextView != null) {
            mSyncTextView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onDisconnected() {
        mContacts.clear();
        if (mSyncTextView != null) {
            mAdapter.setContacts(mContacts);
            mSyncTextView.setVisibility(View.GONE);
        }

    }

    @Override
    public void onCurrentAddress(String address) {
        loadContacts();
    }

    @Override
    public void onSyncContact(String name, String number) {
        Contact contact = new Contact(null, name, BTApplication.getInstance().getCurrentAddress()
                , number);
        mContacts.add(contact);

        mHandler.removeMessages(MSG_SYNC_TIMEOUT);
        mHandler.sendEmptyMessageDelayed(MSG_SYNC_TIMEOUT, SYNC_MAX_TIME);
    }

    @Override
    public void onSyncContactDone() {
        if (isDetach()) {
            return;
        }
        dismissProgressDialog();
        mHandler.removeMessages(MSG_SYNC_TIMEOUT);
        mAdapter.setContacts(mContacts);
        mSyncTextView.setVisibility(View.GONE);

        new Thread() {
            @Override
            public void run() {
                if (isLoadFromDevice) {
                    BTApplication.getInstance().getDaoSession().getContactDao().insertInTx
                            (mContacts);
                }
            }
        }.start();
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnListFragmentInteractionListener {
        void onListFragmentInteraction(Contact item);
    }

    public static ContactListener getContactListener() {
        return sContactListener;
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SYNC_TIMEOUT:
                    if (isDetach()) {
                        return;
                    }
                    dismissProgressDialog();
                    mSyncTextView.setVisibility(View.GONE);
                    break;
            }
        }
    };

    private void showProgressDialog() {
        if (isDetach()) {
            return;
        }
        mProgressDialog = new ProgressDialog(getContext());
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setMessage(getString(R.string.sync_contacts));
        mProgressDialog.show();
    }

    private void dismissProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }
}
